package com.tjoydoorsystem.main;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

import com.tjoydoorsystem.Global;
import com.tjoydoorsystem.R;
import com.tjoydoorsystem.bluetooth.BluetoothLeService;
import com.tjoydoorsystem.receiver.BluetoothReceiver;
import com.tjoydoorsystem.util.DialogUtil;
import com.tjoydoorsystem.util.ScreenUtil;
import com.tjoydoorsystem.util.ToastUtil;


@SuppressWarnings("ALL")
public class WelcomeActivity extends AppCompatActivity {

    private boolean isFirst = true;
    private BluetoothReceiver mGattUpdateReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ScreenUtil.setFullScreen(this);  //全屏
        ScreenUtil.keepScreenLight(this);   //常亮
        ScreenUtil.hideNavigation(this); //隐藏导航栏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        // 注册蓝牙监控广播监听
        mGattUpdateReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(mGattUpdateReceiver, intentFilter);

        //android 6.0以上包括6.0
        if (Build.VERSION.SDK_INT >= 23) {
            CheckPermissions();
        } else {
            //小于6.0直接登陆进去
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        }
    }

    @Override
    protected void onDestroy() {
        Log.i("TAG", "onDestroy");
        super.onDestroy();
        unregisterReceiver(mGattUpdateReceiver);
    }


    /**
     * 权限检测回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == Global.Const.PermissionCallBack) {

            if (grantResults.length != 0) {
                int n = 0;
                for (int grantResult : grantResults) {
                    if (grantResult == PermissionChecker.PERMISSION_GRANTED) {
                        n++;
                    }
                }
                if (n != grantResults.length) {
                    ToastUtil.showMessage(WelcomeActivity.this, "允许权限后应用才能运行！");
                    CheckPermissions();
                    return;
                }

                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));

            } else {
                ToastUtil.showMessage(WelcomeActivity.this, "允许权限后应用才能运行！");
                CheckPermissions();
            }
        }
    }


    /**
     * 设置回调
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Global.Const.PermissionSetting) {
            CheckPermissions();
        }
        // 开启蓝牙时，点击取消使用蓝牙
        if (requestCode == Global.Const.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            ToastUtil.showMessage(WelcomeActivity.this, "您已禁用蓝牙设备");
            finish();
        }
    }

    /**
     * 权限检测
     */
    public void CheckPermissions() {
        //检测权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
            if (!isFirst) {
                //检测权限是否拒绝过
                if (!shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)
                        || !shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)
                        || !shouldShowRequestPermissionRationale(Manifest.permission.BLUETOOTH)) {
                    DialogUtil.showYN(this, "您已拒绝权限，请手动打开设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ToastUtil.showMessage(WelcomeActivity.this, "当前无权限，请授权！");
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", WelcomeActivity.this.getPackageName(), null);
                            intent.setData(uri);
                            startActivityForResult(intent, Global.Const.PermissionSetting);
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    });
                    return;
                }
            }
            //请求权限
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA,
                            Manifest.permission.BLUETOOTH,
                    },
                    Global.Const.PermissionCallBack);

            isFirst = false;

        } else {
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        }
    }



}
